import Scout from "../../flyer/DestructibleFlyer/Scout";
import { Killer } from "../../funcObj/interface/HealthPoint";
import { Location } from "../../info/Predefine";
import NodePoolManager from "../../manager/NodePoolManager";
import Player from "../../player/Player";
import LaunchableFalicity from "../LaunchableFalicity";

const { ccclass, property } = cc._decorator;
/**
 * 侦察机基地
 */
@ccclass
export default class ScoutBase extends LaunchableFalicity {

    @property(cc.Node)
    points: cc.Node = null;

    scoutQueue: Array<cc.Node> = null;

    creating: boolean;

    get count(): number {
        return this.scoutQueue.length;
    }

    init(player: Player): void {
        super.init(player);
        this.scoutQueue = [];
        this.creating = false;
        this.creat();
    }

    /**
     * 加入一台侦察机
     */
    creat() {
        if (this.creating) return;
        this.creating = true;
        this.CreatingProgress.node.active = true;
        this.CreatingProgress.progress = 0;
        cc.tween(this.CreatingProgress)
            .to(8, { progress: 1 })
            .call(() => {
                let scout: cc.Node = NodePoolManager.instance.obtain(NodePoolManager.instance.scout);
                scout.getComponent(Scout).init(this);
                this.scoutQueue.push(scout);
                let spacePoint = this.points.children.find(item => !item["record"]);
                let flyerParent = this.player.flyerParentNode;
                scout.parent = flyerParent;
                scout.position = flyerParent.convertToNodeSpaceAR(spacePoint.convertToWorldSpaceAR(cc.Vec3.ZERO));
                spacePoint["record"] = scout;
                scout.getComponent(cc.Animation).play("scoutFloat");
                this.player.node.emit(Player.EventType.更新飞行物数量, this.facilityType, 1);
            })
            .call(() => {
                this.CreatingProgress.node.active = false;
                this.creating = false;
                if (this.scoutQueue.length < this.facilityInfo.每基地可制造上限) {
                    this.creat();
                }
            })
            .start();
    }

    /**
     * 向目标派遣一个侦察机
     * @param target 
     */
    dispatch(target: Location) {
        super.dispatch(target);
        let scout: cc.Node = this.scoutQueue.shift();
        let spacePoint = this.points.children.find(item => item["record"] === scout);
        spacePoint["record"] = null;

        this.dispatchQueue.push({flyer : scout , target : target});
        this.player.node.emit(Player.EventType.更新飞行物数量, this.facilityType, -1);
        this.creat();
    }

    die(killer: Killer): void {
        super.die(killer);
        this.scoutQueue.forEach(scout => NodePoolManager.instance.recycle(scout));
        this.points.children.forEach(item=>item["record"] = null)
        this.scoutQueue = null;
    }

}
